<template>
  <div class="comment-box">
    <div class="comment-list" v-for="(item, _index) in data" :key="_index">
      <template v-if="index === 1">
        <!-- 评论头像 -->
        <div class="fl comment_img">
          <img :src="item.img" :alt="item.username" />
        </div>
        <!-- 评论内容 -->
        <div class="comment_detail">
          <a href="">{{ item.username }}</a
          >：{{ item.content }}
        </div>
      </template>
      <div v-else class="comment_parent">
        <a href=""
          >{{ item.username }}<span>回复</span>@{{ item.replyUserName }}</a
        >：{{ item.content }}
      </div>
      <!-- 评论时间 -->
      <div class="comment_time">
        <div>
          {{ $date.format(item.time) }}
          <a class="fr" @click="commentClick">回复</a>
        </div>
      </div>
      <template v-if="item.children && item.children.length">
        <comment
          :data="item.children"
          :index="index + 1"
          :scroll-bottom="scrollBottom"
        ></comment>
      </template>
    </div>
  </div>
</template>

<script>
export default {
  name: "Comment",
  props: {
    index: {
      // 评论树级别，级别越深，index越大，1 表示第一级评论
      type: Number,
      default: 1
    },
    data: {
      // 评论列表，改成符合格式的对象
      type: Array,
      required: true
    },
    scrollBottom: {
      type: Function
    }
  },
  methods: {
    // 返回顶部
    commentClick(event) {
      // https://blog.csdn.net/qq_24729895/article/details/79049066 (解决返回顶部/底部无效)
      document.documentElement.scrollTop =
        document.documentElement.scrollHeight;
      if (!document.documentElement.scrollTop) {
        document.body.scrollTop = document.documentElement.scrollHeight;
      }
      this.$emit("scroll-bottom");
      if (typeof this.scrollBottom === "function") this.scrollBottom(event);
    }
  }
};
</script>

<style lang="scss" scoped>
$comment: "comment";

.#{$comment}_img img {
  margin-top: 5px;
  border-radius: 4px;
}

.#{$comment}_img,
.#{$comment}_img img {
  height: 30px;
  width: 30px;
}

.#{$comment}_detail {
  margin-left: 40px;
  font-size: 12px;
  letter-spacing: 1px;
  a {
    color: #d1694f;
    font-size: 12px;
  }
}
.#{$comment}_parent {
  @extend .#{$comment}_detail;
  padding: 5px;
  background-color: #ececec;
  color: #303133;
  border-radius: 0.25rem;
  span {
    cursor: default;
    color: #303133;
  }
}

.#{$comment}-list {
  margin: 10px 0;
  padding: 0 10px;
}

.#{$comment}_time {
  margin-left: 40px;
  font-size: 12px;
  color: #b0b2b7;
  a {
    font-size: 12px;
  }
}
</style>
